<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\controller;

use app\madmin\service\LesseeService;
use think\App;
use think\Exception;
use think\facade\Db;
use think\facade\Request;
class WxUrl extends BaseAction
{

    public function __construct(App $app)
    {
        parent::__construct($app);
        $lesseeService = new LesseeService();
        list($code, $entry) = $lesseeService->entry();
        if ($this->request->rule()->getRule() != "wxurl/preview") {
            if (empty($entry) || !in_array(2, $entry)) {
                throw new Exception("不支持该端操作",HTTP_NOTACCEPT);
            }
        }
    }

    public function index(Request $request)
    {
        $url = url("wxurl/check", ["mall" => $this->user->mall_id], '', true)->build();
        return json(['URL' => $url], HTTP_SUCCESS);
    }

    public function check()
    {

        $mall = input("get.mall");

        $configuration = Db::name("configuration")
            ->where(['type' => 'wx', 'mall_id' => $mall])
            ->value('configuration');
        if (!$configuration) {
            return false;
        }

        $configuration = json_decode($configuration, true);

        //微信验证
        $signature = input("get.signature");
        $timestamp = input("get.timestamp");
        $nonce = input("get.nonce");

        $token = $configuration['Token'];
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr === $signature) {
            echo input("get.echostr");
            die;
        }

        echo false;
        die;
    }

    public function preview()
    {
        global $user;
        $url = Request::domain() . "/h5/#/pages/index/index?mall_id=" . $user->mall_id;
        return json(['msg' => $url], HTTP_SUCCESS);
    }

}
